package com.gray.blog.common.util.thread;

import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.core.thread.ThreadUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NamedThreadPool {

    private static final String POOL_NAME_PREFIX = "pool_";

    public static ExecutorService newFixedThreadPool(int number, String name) {
        return new ThreadPoolExecutor(number, number, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(POOL_NAME_PREFIX + name, ThreadUtil.currentThreadGroup(), false));
    }

    public static ExecutorService newThreadPool(int corePoolSize, int maximumPoolSize, String name) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(),
            new NamedThreadFactory(POOL_NAME_PREFIX + name, ThreadUtil.currentThreadGroup(), false));
    }

    public static ExecutorService newThreadPool(int corePoolSize, int maximumPoolSize, int queueSize, String name, RejectedExecutionHandler handler) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(queueSize),
            new NamedThreadFactory(POOL_NAME_PREFIX + name, ThreadUtil.currentThreadGroup(), false), handler);
    }
}